package hu.uszeged.inf.wlab.stunner.database.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.provider.BaseColumns;
import android.text.TextUtils;

/**
 * Helper for building selection clauses for {@link SQLiteDatabase}. Each appended clause is combined using {@code AND}. This class is
 * <em>not</em> thread safe.
 * 
 * @author szelezsant
 */
public class SelectionBuilder {

	/** Name of the tables where the query will run. You can specify here the JOIN statement. */
	private String tables = null;
	/** Projection map. */
	private final Map<String, String> projectionMap = new HashMap<String, String>();
	/** Selection clause as a string. */
	private final StringBuilder selectionString = new StringBuilder();
	/** The list of selection arguments. */
	private final List<String> selectionArguments = new ArrayList<String>();

	/**
	 * Reset any internal state, allowing this builder to be recycled.
	 * 
	 * @return the current instance after resetting its attributes.
	 */
	public SelectionBuilder reset() {
		tables = "";
		selectionString.setLength(0);
		selectionArguments.clear();
		projectionMap.clear();
		return this;
	}

	/**
	 * Append the given selection clause to the internal state. Each clause is surrounded with parenthesis and combined using {@code AND}.
	 * 
	 * @param selection - the where clause
	 * @param selectionArgs - the selection argument values
	 * @return the current instance after setting the where clause.
	 */
	public SelectionBuilder where(final String selection, final String... selectionArgs) {
		if (TextUtils.isEmpty(selection)) {
			if (selectionArgs != null && selectionArgs.length > 0) {
				throw new IllegalArgumentException(
						"Valid selection required when including arguments=");
			}

			return this;
		}

		if (selectionString.length() > 0) {
			selectionString.append(" AND ");
		}

		selectionString.append("(").append(selection).append(")");
		if (selectionArgs != null) {
			Collections.addAll(selectionArguments, selectionArgs);
		}

		return this;
	}

	/**
	 * Sets the tables name. You can specify here the JOIN statement.
	 * 
	 * @param table - the name of the tables to be set.
	 * @return the current instance with the updated table information.
	 */
	public SelectionBuilder setTable(final String table) {
		tables = table;
		return this;
	}

	/**
	 * Checks if the table name is set.
	 */
	private void assertTable() {
		if (TextUtils.isEmpty(tables)) {
			throw new IllegalStateException("Table not specified");
		}
	}

	/**
	 * Puts the fully specified column names to the projection map.
	 * 
	 * @param column - the name of the column
	 * @param table - the name of the table.
	 * @return the current instance with updated projection map.
	 */
	public SelectionBuilder mapToTable(final String column, final String table) {
		final String qualifiedName = addQualifierPrefix(table, column);
		projectionMap.put(qualifiedName, qualifiedName + DatabaseConstants.AS_ALIAS_LITERAL + qualifiedName);
		return this;
	}

	/**
	 * Return selection string for current internal state.
	 * 
	 * @return the where clause as a string.
	 * @see #getSelectionArgs()
	 */
	public String getSelection() {
		return selectionString.toString();
	}

	/**
	 * Return selection arguments for current internal state.
	 * 
	 * @return the selection arguments as a String array.
	 * @see #getSelection()
	 */
	public String[] getSelectionArgs() {
		return selectionArguments.toArray(new String[selectionArguments.size()]);
	}

	/**
	 * Puts each of the given columns to the projection map.
	 * 
	 * @param columns - the input columns to be mapped
	 */
	private void mapColumns(final String[] columns) {
		for (int i = 0; i < columns.length; i++) {
			final String target = projectionMap.get(columns[i]);
			if (target != null) {
				columns[i] = target;
			}
		}
	}

	@Override
	public String toString() {
		return "SelectionBuilder[table=" + tables + ", selection=" + getSelection()
				+ ", selectionArgs=" + Arrays.toString(getSelectionArgs()) + "]";
	}

	/**
	 * Execute query using the current internal state as {@code WHERE} clause.
	 * 
	 * @param database - the database to perform the query on.
	 * @param projection - the projection columns to be displayed
	 * @param orderBy - the order by clause.
	 * @return the {@link Cursor} object with the query result
	 */
	public Cursor query(final SQLiteDatabase database, final String[] projection, final String orderBy) {
		return query(database, createProjectionAliases(projection), null, null, orderBy, null);
	}

	/**
	 * Execute query using the current internal state as {@code WHERE} clause.
	 * 
	 * @param database - the database to perform the query on.
	 * @param columns - the projection columns to be displayed
	 * @param groupBy - the group by clause
	 * @param having - the having clause
	 * @param orderBy - the order by clause
	 * @param limit - the number of results to be listed
	 * @return the {@link Cursor} object with the query result
	 */
	public Cursor query(final SQLiteDatabase database, final String[] columns, final String groupBy,
			final String having, final String orderBy, final String limit) {
		assertTable();
		if (columns != null) {
			mapColumns(columns);
		}
		return database.query(tables, columns, getSelection(), getSelectionArgs(), groupBy, having,
				orderBy, limit);
	}

	/**
	 * Execute update using the current internal state as {@code WHERE} clause.
	 * 
	 * @param database - the database to perform the update on
	 * @param values - the {@link ContentValues} instance filled with the attributes.
	 * @return the number of rows affected
	 */
	public int update(final SQLiteDatabase database, final ContentValues values) {
		assertTable();
		return database.update(tables, values, getSelection(), getSelectionArgs());
	}

	/**
	 * Execute delete using the current internal state as {@code WHERE} clause.
	 * 
	 * @param database - the database to perform the delete operation on.
	 * @return the number of rows affected
	 */
	public int delete(final SQLiteDatabase database) {
		assertTable();
		return database.delete(tables, getSelection(), getSelectionArgs());
	}

	/**
	 * Completes the projection string with the aliases mapped to the column names.
	 * 
	 * @param projectionIn - the current projection clause
	 * @return projection with aliases
	 */
	private String[] createProjectionAliases(final String[] projectionIn) {
		if (null != projectionIn && projectionIn.length > 0) {
			final String[] result = new String[projectionIn.length];
			for (int i = 0; i < projectionIn.length; i++) {
				final String projection = projectionIn[i];
				if (projection.contains(DatabaseConstants.AS_ALIAS_LITERAL) || projection.contains(DatabaseConstants.AS_ALIAS_LITERAL)) {
					result[i] = projectionIn[i];
				} else if (projection.endsWith(BaseColumns._ID)) {
					result[i] = projection.concat(DatabaseConstants.AS_ALIAS_LITERAL + BaseColumns._ID);
				} else {
					result[i] = projection.concat(DatabaseConstants.AS_ALIAS_LITERAL + projection.replace(".", ""));
				}
			}
			return result;
		}
		return projectionIn;
	}

	/**
	 * Create left join relation over tables.
	 * 
	 * @param table - the right table, which join to the other table
	 * @param joinerTable - the joiner table
	 * @param tableColumn - the right table column
	 * @param joinerTableColumn - the joiner table column
	 * @return a left join statement string
	 */
	public static String createLeftJoinStatement(final String table, final String tableColumn, final String joinerTable,
			final String joinerTableColumn) {
		final StringBuilder builder = new StringBuilder();
		builder.append(" LEFT JOIN ");
		builder.append(joinerTable);
		builder.append(" ON ");
		builder.append(addQualifierPrefix(joinerTable, joinerTableColumn));
		builder.append(" = ");
		builder.append(addQualifierPrefix(table, tableColumn));
		return builder.toString();
	}

	/**
	 * Add a table name qualifier prefix to column name in tableName.columnName format.
	 * 
	 * @param table - the prefix of the column.
	 * @param columnName - the name of the column.
	 * @return qualified name of the column.
	 */
	public static String addQualifierPrefix(final String table, final String columnName) {
		final StringBuilder builder = new StringBuilder();
		builder.append(table);
		builder.append(".");
		builder.append(columnName);
		return builder.toString();
	}

	/**
	 * Gets the alias name in the format produced by the {@link SelectionBuilder#createProjectionAliases(String[])} method.
	 * 
	 * @param table - the name of the table
	 * @param columnName - the name of the column
	 * @return the alias
	 */
	public static String getAliasName(final String table, final String columnName) {
		return table.concat(columnName);
	}
}
